package com.zg.job.batch.first;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/2/19 15:07
 */

import com.zg.job.config.CustomJobExecutionListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 简单的任务
 *
 * @author Mr.NaCl
 * @since 2024/8/21
 */
@Component
@Slf4j
public class FirstJobDo {

    @Resource
    private JobBuilderFactory jobBuilderFactory;
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private CustomJobExecutionListener customJobExecutionListener;

    @Bean(name="firstJob")
    public Job firstJob() {
        return jobBuilderFactory.get("firstJob")
                .start(step())
                .incrementer(new RunIdIncrementer())
                .listener(customJobExecutionListener)
                .build();
    }

    private Step step() {
        return stepBuilderFactory.get("step")
                .tasklet((contribution, chunkContext) -> {
                   log.info("execute  step1....");
                    return RepeatStatus.FINISHED;
                }).listener(new StepListener()).build();
    }

    public class StepListener implements StepExecutionListener {
        @Override
        public void beforeStep(StepExecution stepExecution) {
            log.info(stepExecution.getStepName()+"开始: " + stepExecution.getStepName());
        }

        @Override
        public ExitStatus afterStep(StepExecution stepExecution) {
            log.info("Step处理数量: " + stepExecution.getReadCount());
            log.info("Step跳过数量: " + stepExecution.getSkipCount());
            return stepExecution.getExitStatus();
        }
    }

}